const app = getApp()
let musiclist = []
let playingMusicIndex = 0
// 获取全局唯一的背景音频管理器
const backgroundAudioManager = wx.getBackgroundAudioManager()

Page({
    /**
     * 页面的初始数据
     */
    data: {
        picUrl: '',
        isPlaying: false,
        isLyricShow: false,
        lyric: '',
        // 是否为同一首歌
        isSame: false,
    },   

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        playingMusicIndex = options.index
        musiclist = wx.getStorageSync('musiclist')
        this._loadMusicDetail(options.musicId)
    },

    // 初始化当前歌曲
    _loadMusicDetail(musicId) {
        // 判断是否为同一首歌
        this.setData({
            isSame: musicId === app.getPlayingMusicId()
        })

        // 若是同一首歌，暂停音频播放
        if (this.data.isSame) {
            backgroundAudioManager.stop()
        }

        // 获取缓存的歌曲数据
        let music = musiclist[playingMusicIndex]
        wx.setNavigationBarTitle({
            title: music.name,
        })
        this.setData({
            picUrl: music.al.picUrl,
            isPlaying: false
        })
        // 设置当前播放的歌曲id（全局变量）
        app.setPlayingMusicId(musicId)

        // 获取待播放歌曲的url
        wx.showLoading({
            title: '歌曲加载中',
        })
        wx.cloud.callFunction({
            name: 'music',
            data: {
                musicId,
                $url: 'musicUrl'
            }
        }).then(res => {
            console.log('歌曲url', res)
            let result = res.result
            if (result.data[0].url === null) {
                wx.showToast({
                    icon: 'error',
                    title: '无权限播放',
                })
                return
            }

            if (!this.data.isSame) {
                backgroundAudioManager.src = result.data[0].url
                backgroundAudioManager.title = music.name
                // 保存播放历史记录
                this.savePlayHistory()
            }

            this.setData({
                isPlaying: true
            })
            wx.hideLoading()

            // 获取歌词
            this._getLyric(musicId)
        })
    },

    // 获取歌词
    _getLyric(musicId) {
        wx.cloud.callFunction({
            name: 'music',
            data: {
                musicId,
                $url: 'lyric'
            }
        }).then(res => {
            console.log('歌词', res)
            let lyric = '暂无歌词'
            const lrc = res.result.lrc
            if (lrc) {
                lyric = lrc.lyric
            }
            this.setData({
                lyric
            })
        })
    },

    // 点击“播放”按钮触发：切换播放状态
    togglePlaying() {
        if (this.data.isPlaying) {
            backgroundAudioManager.pause()
        } else {
            backgroundAudioManager.play()
        }

        this.setData({
            isPlaying: !this.data.isPlaying
        })
    },

    // 监听“进度条”事件：播放
    onPlay() {
        this.setData({
            isPlaying: true
        })
    },

    // 监听“进度条”事件：暂停
    onPause() {
        this.setData({
            isPlaying: false
        })
    },

    // 点击“上一首”按钮触发
    onPrev() {
        playingMusicIndex--
        if (playingMusicIndex < 0) {
            playingMusicIndex = musiclist.length - 1
        }
        this._loadMusicDetail(musiclist[playingMusicIndex].id)
    },

    // 点击“下一首”按钮触发
    onNext() {
        playingMusicIndex++
        if (playingMusicIndex === musiclist.length) {
            playingMusicIndex = 0
        }
        this._loadMusicDetail(musiclist[playingMusicIndex].id)
    },

    // 切换歌词的显隐
    onChangeLyricShow() {
        this.setData({
            isLyricShow: !this.data.isLyricShow
        })
    },

    // 同步进度条和歌词的播放进度
    timeUpdate(event) {
        this.selectComponent('.lyric').update(event.detail.currentTime)
    },

    // 保存播放历史记录
    savePlayHistory() {
        const music = musiclist[playingMusicIndex]
        const openid = app.globalData.openid
        const history = wx.getStorageSync(openid)
        let hasSaved = false

        for (let i = 0, len = history.length; i < len; i++) {
            if (history[i].id === music.id) {
                hasSaved = true
                break
            }
        }
        if (!hasSaved) {
            history.unshift(music)
            wx.setStorage({
                key: openid,
                data: history
            })
        }
    }
})